var map;
var layerType = "";
var locMarker;//定位
var layerArr = [];
var selectJgid = "";
var selectColor = "";

var baseLayers;
var basemaps;
var overlayLayers = {};
var defaultBaseLayer;
var crs;
if (mapConfig.isOnline == "true") {
    layerType = "SL";
    console.log("调用互联网地图...");
    var mapOptions = {
        maxZoom: 18,
        minZoom: 10,
    };
    var normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', mapOptions),
        normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', mapOptions),
        imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', mapOptions),
        imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', mapOptions);
    var normal = L.layerGroup([normalm, normala], {
        label: '天地图矢量',
        iconURL: '../plugin/leaflet/images/basemap-tdtsl.png',
        crs: L.CRS.EPSG3857,
    });
    var image = L.layerGroup([imgm, imga], {
        label: '天地图影像',
        iconURL: '../plugin/leaflet/images/basemap-tdtyx.png',
        crs: L.CRS.EPSG3857,
    });
    basemaps = [normal, image];
    baseLayers = {
        "地图": normal,
        "影像": image
    };
    defaultBaseLayer = normal;
    crs = L.CRS.EPSG3857;
}
else if (mapConfig.isOnline == "false") {
    layerType = "TDTSL";
    console.log("调用内网地图...");
    var tdtLayerOptions = {
        minZoom: 0,
        maxZoom: 20,
    };
    var pgisLayerOptions = {
        minZoom: 0,
        maxZoom: 20,
        tms: true
    };
    var baseTDTUrl = "http://10.34.1.91:7001/PGIS_S_LWTileMap_Tdt/Maps/{mapName}/EzMap?Service=getImage&Type=RGB&ZoomOffset=0&Col={x}&Row={y}&Zoom={z}&V=1.0.0";
    var basePGISUrl = "http://10.34.1.91:7001/PGIS_S_LWTileMap/Maps/{mapName}/EzMap?Service=getImage&Type=RGB&ZoomOffset=0&Col={x}&Row={y}&Zoom={z}&V=0.3";
    var baseGDUrl = "http://10.32.203.96/PGIS_S_TileMapServer/Maps/{mapName}/EzMap?Service=getImage&Type=RGB&ZoomOffset=0&Col={x}&Row={y}&Zoom={z}&V=1.0.0";
    //天地图矢量
    var tdtSlUrl = baseTDTUrl.replace("{mapName}", "ZJLWSL");
    var tdtSlMap = L.tileLayer(tdtSlUrl, tdtLayerOptions);
    //天地图影像
    var tdtYxUrl = baseTDTUrl.replace("{mapName}", "ZJLWYX");
    var tdtYxMap = L.tileLayer(tdtYxUrl, tdtLayerOptions);
    //天地图矢影
    var tdtSyUrl = baseTDTUrl.replace("{mapName}", "ZJLWSY");
    var tdtSyMap = L.tileLayer(tdtSyUrl, tdtLayerOptions);

    //高德矢量
    var gdslUrl = baseGDUrl.replace("{mapName}", "GDSLDT");
    var gdslMap = L.tileLayer(gdslUrl, tdtLayerOptions);

    //矢量地图
    // var slUrl = basePGISUrl.replace("{mapName}", "SL");
    var slUrl = basePGISUrl.replace("{mapName}", "ZJSL");
    var slMap = L.tileLayer(slUrl, pgisLayerOptions);
    //影像地图
    var yxUrl = basePGISUrl.replace("{mapName}", "YX");
    var yxMap = L.tileLayer(yxUrl, pgisLayerOptions);
    //矢量影像地图
    var slyxUrl = basePGISUrl.replace("{mapName}", "SLYX");
    var slyxMap = L.tileLayer(slyxUrl, pgisLayerOptions);

    var tdtsl = L.layerGroup([tdtSlMap], {
        label: '天地图矢量',
        iconURL: '../plugin/leaflet/images/basemap-tdtsl.png',
        crs: getCrs('tdt')
    });
    var tdtyx = L.layerGroup([tdtYxMap], {
        label: '天地图影像',
        iconURL: '../plugin/leaflet/images/basemap-tdtyx.png',
        crs: getCrs('tdt')
    });
    var tdtsy = L.layerGroup([tdtSyMap], {
        label: '天地图矢影',
        iconURL: '../plugin/leaflet/images/basemap-tdtsy.png',
        crs: getCrs('tdt')
    });
    var pgissl = L.layerGroup([slMap], {
        label: '矢量地图',
        iconURL: '../plugin/leaflet/images/basemap-pgissl.png',
        crs: getCrs('pgis')
    });
    var pgisyx = L.layerGroup([yxMap], {
        label: '影像地图',
        iconURL: '../plugin/leaflet/images/basemap-pgisyx.png',
        crs: getCrs('pgis')
    });
    var pgissy = L.layerGroup([slyxMap], {
        label: '矢影地图',
        iconURL: '../plugin/leaflet/images/basemap-pgissy.png',
        crs: getCrs('pgis')
    });
    var gdsl = L.layerGroup([gdslMap], {
        label: '高德矢量',
        iconURL: '../plugin/leaflet/images/basemap-gdsl.png',
        crs: getCrs('tdt')
    });
    basemaps = [tdtsl, tdtyx, tdtsy, pgissl, pgisyx, pgissy, gdsl];
    baseLayers = {
        "天地图矢量": tdtSlMap,
        "天地图影像": tdtYxMap,
        "天地图矢影": tdtSyMap,
        "矢量地图": slMap,
        "影像地图": yxMap,
        "矢影地图": slyxMap,
        "高德矢量": gdslMap,
    };
    defaultBaseLayer = tdtSlMap;
}
else {
    layer.msg("系统参数表中'是否在线'参数配置错误！");
}

//公安内网获取坐标系
function getCrs(type) {
    var crs = L.CRS.EPSG3857;
    var initResolution;
    var res = [];
    var origin;
    if (type == "pgis") {
        for (var i = 0; i < 23; i++) {
            res[i] = 2 / Math.pow(2, i);
        }
        origin = [0, 0];
        crs = new L.Proj.CRS("PGIS:4490", "+proj=longlat +ellps=GRS80 +no_defs", {
            origin: origin,
            resolutions: res,
            bounds: L.bounds([180, 0], [0, 90]),
        });
    }
    else if (type == "tdt") {
        for (var i = 0; i < 23; i++) {
            res[i] = 1.4062500262315825 / Math.pow(2, i);
        }
        origin = [-180, 90];
        crs = new L.Proj.CRS("TDT:4490", "+proj=longlat +ellps=GRS80 +no_defs", {
            origin: origin,
            resolutions: res,
            // bounds: L.bounds([180, -90], [-180, 90]),
        });
    }
    crs.distance = function (latlng1, latlng2) {
        var rad = Math.PI / 180,
            R = 6378137,
            lat1 = latlng1.lat * rad,
            lat2 = latlng2.lat * rad,
            a = Math.sin(lat1) * Math.sin(lat2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
        return R * Math.acos(Math.min(a, 1));
    };
    return crs;
}

var map = L.map("map", {
    zoominfoControl: false,
    positionControl: true,
    center: mapConfig.centerPoint,
    zoom: mapConfig.defaultLevel,
    // crs: defaultBaseLayer.options.crs,
    // layers: [defaultBaseLayer],
    zoomControl: false
});

/**
 * 地图控件
 */
//全屏
L.control.fullscreen({position: "topright"}).addTo(map);
//全图
L.control.fullbounds({position: "topright"}).addTo(map);
//地图切换
// L.control.layers(baseLayers, overlayLayers, {position: "bottomright", collapsed: true}).addTo(map);
L.control.basemaps({basemaps: basemaps}).addTo(map);   //默认加载第一个底图
//层级
L.control.zoominfo({position: 'bottomright'}).addTo(map);
//添加坐标位置
//L.control.mousePosition().addTo(map);
//地图比例尺
L.control.scale({position: "bottomleft", metric: true, imperial: false}).addTo(map);

map.addEventListener("baselayerchange", baselayerchange);

function baselayerchange(target) {
    console.log(target.options.label);
    if(map.isOnline=="true"){
        if (target.options.label == "天地图影像") {
            layerType = "YX";
        } else {
            layerType = "SL";
        }
    }else{
        if (target.options.label == "天地图矢量") {
            layerType = "TDTSL";
        }else if(target.options.label == "天地图影像") {
            layerType = "TDTYX";
        }else if(target.options.label == "天地图矢影") {
            layerType = "TDTSY";
        }else if(target.options.label == "矢量地图") {
            layerType = "ZJSL";
        }else if(target.options.label == "影像地图") {
            layerType = "ZJYX";
        }else if(target.options.label == "矢影地图") {
            layerType = "SLYX";
        }else if(target.options.label == "高德矢量") {
            layerType = "GDSL";
        }
    }
}
//测距
var measureControl = L.control.measureControl({position: 'topright'}).addTo(map);
//测面
var measureAreaControl = L.control.measureAreaControl({
    primaryLengthUnit: 'qm',
    primaryAreaUnit: 'pfqm',
    activeColor: '#a72204',
    completedColor: '#d22a00',
    decPoint: '.',
    thousandsSep: ',',
}).addTo(map);
//测距测面清除控件
L.control.measureClearControl({
    position: 'topright',
    measureControl: measureControl,
    measureAreaControl: measureAreaControl
}).addTo(map);

//地图截屏
L.printScreen({
    title: "打印",
    position: "topright",
    sizeModes: ['Current'],
    exportOnly: false,
}).addTo(map);
//地图打印
L.printScreen({
    title: "截屏",
    position: "topright",
    sizeModes: ['Current'],
    exportOnly: true,
}).addTo(map);

map.on('pm:remove', function (e) {
    console.log('pm:remove event fired. See console for details');
    //layer.msg('pm:remove event fired. See console for details');
    console.log(e);
    if (tempRemove == false && layerRemove == true) {
        //layer.msg("执行后台删除功能！");
    } else {
        //layer.msg("执行后台删除功能！");
    }
});

map.on('pm:globaleditmodetoggled', function (e) {
    //layer.msg("toggled");
    console.log(e.enabled);
    if (e.enabled == false) {
        tempRemove = false;//关闭临时移除模式
        layerRemove = true; //开启后台删除模式
    } else {
        tempRemove = true;//开启临时移除模式
        layerRemove = false; //关闭后台删除模式
    }
});

if (username == "admin" || roleName != "管理员") {
    map.pm.addControls({
        drawRectangle: false,
        drawCircle: false,
        drawMarker: false,
        drawPolygon: false,
        editPolygon: false,
        drawPolyline: false,
        deleteLayer: false,
        cutPolygon: false
    });
} else {
    map.pm.addControls({
        drawRectangle: false,
        drawCircle: false,
        drawMarker: false,
        drawPolygon: false,
        editPolygon: false,
        drawPolyline: false,
        deleteLayer: false,
        cutPolygon: false,
        removalMode: false
    });
}

map.pm.toggleGlobalEditMode({
    allowSelfIntersection: false,
    preventMarkerRemoval: false,
    preventVertexEdit: false,
});

// map.addEventListener("zoom",zoomChanged);
// function zoomChanged(e) {
//    $('#currentLevel').html("<strong>层级："+map.getZoom()+"</strong>");
// }

//鹰眼图
//var osmAttrib='Map data &copy; OpenStreetMap contributors';
//var osm2 = new L.TileLayer(normal, {minZoom: 0, maxZoom: 20, attribution: osmAttrib });
//var miniMap = new L.Control.MiniMap(osm2, { toggleDisplay: true , minimized: true}).addTo(map);
var regionJson;
map.pm.disableDraw('Poly');
const geoJsonData = {
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            properties: {},
            geometry: {
                type: 'Polygon',
                coordinates: JSON.parse(regionJson == null || regionJson == "" ? "[]" : regionJson)
            }
        }
    ]
};
const geoJsonLayer = L.geoJson(null, {
    pmIgnore: true,
    style: function (geoJsonFeature) {
        return {weight: 6, color: 'red', fill: false, fillColor: '#fff', fillOpacity: 0};
    }
});
geoJsonLayer.addData(geoJsonData);
geoJsonLayer.addTo(map);
if (regionJson != "") {
    map.fitBounds(geoJsonLayer.getBounds());
}

map.on('pm:drawstart', function (e) {
    var layer = e.workingLayer;
});
var layer;
map.on('pm:drawend', function (e) {
    var obj = e.target._targets;
    layer = null;
    var maxkey = 3;
    for (var key in obj) {
        //console.log(key , obj[key]);
        if (key > maxkey) maxkey = key;
        layer = obj[key];
    }
    if (layer != null) {
        layerArr.push(layer);
    }
    //管理员则不绑定地图点击事件
    if (username != "admin") {
        if (map.hasLayer(layer)) {
            layer.on("click", function (e) {
                boundRegion(layer);
            })
        }
    }
});

function mergeMap() {
    var url = '/regionAllot/load/mergemap/map';
    var contentUrl = '<iframe name="addMapInfo" id="addMapInfo" style="width:100%; height:100%" frameborder="0" src="' + url + '" scrolling="no"></iframe>';
    var win = $('#win').window(
        {
            title: "合成下载", // 标题
            width: '400',
            height: '240',
            modal: 'true',// 模态
            minimizable: false, //窗口缩小
            closed: 'true', // 默认关闭
            collapsible: false, // 折叠
            maximizable: false,
            content: contentUrl,
            loadingMessage: '正在加载数据请稍等......',
            animate: true,
            resizable: false,
            onBeforeClose: function () {
            }
        }
    );
    $('#win').css("overflow", "hidden");
    win.window('open');
}

function boundRegion(layer) {
    selectJgid = layer.id;
    selectColor = layer.color;
    var url = '/regionAllot/load/update/' + layer.id;
    var contentUrl = '<iframe name="addMapInfo" id="addMapInfo" style="width:100%; height:100%" frameborder="0" src="' + url + '" scrolling="no"></iframe>';
    var win = $('#win').window(
        {
            title: "指定" + jgmc + "区域子区域", // 标题
            width: '400',
            height: '240',
            modal: 'true',// 模态
            minimizable: false, //窗口缩小
            closed: 'true', // 默认关闭
            collapsible: false, // 折叠
            maximizable: false,
            content: contentUrl,
            loadingMessage: '正在加载数据请稍等......',
            animate: true,
            resizable: false,
            onBeforeClose: function () {
            }
        }
    );
    $('#win').css("overflow", "hidden");
    win.window('open');
}
/*
 四种定位方式：
 1、map.panTo([50, 30]);
 2、map.panTo({lon: 30, lat: 50});
 3、map.panTo({lat: 50, lng: 30});
 4、map.panTo(L.latLng(50, 30));
 */

//定位 var pnt = [31.71 , 119.38];
function toLocPnt(pnt, i) {
    map.panTo(pnt);
    if (typeof(i) == "undefined") {
        i = '';
    }
    var redIcon = L.icon({
        iconUrl: 'images/red-' + i + '.png',
        iconSize: [21, 29],
        iconAnchor: [21, 29],
        popupAnchor: [0, 0],
        shadowUrl: '',
        shadowSize: [0, 0],
        shadowAnchor: [0, 0]
    });
    locMarker = L.marker(pnt, {icon: redIcon}).addTo(map);
}
//闪烁定位
function toLocFlash(pnt) {
    map.panTo(pnt);
    locMarker = L.marker(pnt).addTo(map);
    var pulsingIcon = new L.icon.pulse({iconSize: [20, 20], color: 'red'});
    falshMarker = L.marker(pnt, {icon: pulsingIcon}).addTo(map);

}
//带标题定位
function toLocPntAndPop(pnt, title) {
    map.panTo(pnt);
    if (typeof(title) == "undefined") {
        title = '';
    }
    var pulsingIcon = new L.icon.pulse({iconSize: [20, 20], color: 'red'});
    locMarker = L.marker(pnt, {icon: pulsingIcon}).addTo(map);
    L.marker(pnt).addTo(map).bindPopup('名称：' + title).openPopup();
}
//
//获取地图数据
function getMapJson() {
    var geoJson = layer.toGeoJSON();
    var latlngsJson = JSON.stringify(geoJson.geometry.coordinates);
    return latlngsJson;
}

function setLayerStyle(jgid, color) {
    layer.id = jgid;
    layer.setStyle({color: color});
}


function toDowloadExtent1() {
    var topTileFromX = -180;
    var topTileFromY = 90;

    var tdtScale = {
        1: 0.7031250131157912,
        2: 0.3515625065578956,
        3: 0.1757812532789478,
        4: 0.0878906266394739,
        5: 0.04394531331973695,
        6: 0.021972656659868476,
        7: 0.010986328329934238,
        8: 0.005493164164967119,
        9: 0.0027465820824835595,
        10: 0.0013732910412417797,
        11: 0.0006866455206208899,
        12: 0.00034332276031044494,
        13: 1.7166138015522247 - 04,
        14: 8.583069007761123E-05,
        15: 4.291534503880562E-05,
        16: 2.145767251940281E-05,
        17: 1.0728836259701404E-05,
        18: 5.364418129850702E-06,
        19: 2.682209064925351E-06
    };

    var level = document.getElementById("level").value;

    var coef = tdtScale[level] * 256;
    var bounds = map.getBounds();
    var northWestLatlng = bounds.getNorthWest();
    var southEastLatlng = bounds.getSouthEast();

    var colmin = Math.round((northWestLatlng.lng - topTileFromX) / coef);
    var rowmin = Math.round((topTileFromY - northWestLatlng.lat) / coef);

    var colmax = Math.round((southEastLatlng.lng - topTileFromX) / coef);
    var rowmax = Math.round((topTileFromY - southEastLatlng.lat) / coef);

    var blob = new Blob(["type=" + layerType + "\r\nlevel=" + level + "\r\ncolmin=" + colmin + "\r\nrowmin=" + rowmin + "\r\ncolmax=" + colmax + "\r\nrowmax=" + rowmax], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "坐标范围.txt");

}

function lon2Mercator(px) {
    var x = px * 20037508.3427892 / 180;
    return x;
}

function lat2Mercator(py) {
    var y;
    y = Math.log(Math.tan((90 + py) * Math.PI / 360)) / (Math.PI / 180);
    y = y * 20037508.3427892 / 180;
    return y;
}

function toDowloadExtent() {
    var topTileFromX = -20037508.3427892;
    var topTileFromY = 20037508.3427892;
    var tdtScale = {
        18: 0.597164283559817,
        17: 1.19432856685505,
        16: 2.38865713397468,
        15: 4.77731426794937,
        14: 9.55462853563415,
        13: 19.1092570712683,
        12: 38.2185141425366,
        11: 76.4370282850732,
        10: 152.8740565704,
        9: 305.7481128,
        8: 611.49622628138,
        7: 1222.99245256249,
        6: 2445.98490512499,
        5: 4891.96981024998,
        4: 9783.93962049996,
        3: 19567.8792409999,
        2: 39135.7584820001,
        1: 78271.5169639999
    };

    var level = document.getElementById("level").value;

    var coef = tdtScale[level] * 256;

    var bounds = map.getBounds();
    var northWestLatlng = bounds.getNorthWest();
    var southEastLatlng = bounds.getSouthEast();

    var colmin = Math.round((lon2Mercator(northWestLatlng.lng) - topTileFromX) / coef);
    var rowmin = Math.round((topTileFromY - lat2Mercator(northWestLatlng.lat)) / coef);

    var colmax = Math.round((lon2Mercator(southEastLatlng.lng) - topTileFromX) / coef);
    var rowmax = Math.round((topTileFromY - lat2Mercator(southEastLatlng.lat)) / coef);

    var blob = new Blob(["type=" + layerType + "\r\nlevel=" + level + "\r\ncolmin=" + colmin + "\r\nrowmin=" + rowmin + "\r\ncolmax=" + colmax + "\r\nrowmax=" + rowmax], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "坐标范围.txt");

}
//合成下载
function toDowloadMap(level) {
    if(mapConfig.isOnline == "true"){
        //在线
        toDowloadMapOnline(level);
    }else{
        //
        if(layerType == "ZJSL"||layerType == "ZJYX"||layerType == "SLYX"){
            toDowloadMapPgis(level);
        }else {
            toDowloadMapOffline(level);
        }
    }
}

//地图下载
function toDowloadMapOffline() {
    var topTileFromX = -180;
    var topTileFromY = 90;

    var tdtScale = {
        20: 1.3411045074462875E-06,
        19: 2.682209014892575E-06,
        18: 5.36441802978515E-06,
        17: 1.07288360595703E-05,
        16: 2.1457672119140625E-05,
        15: 4.29153442382814E-05,
        14: 8.58306884765629E-05,
        13: 0.000171661376953125,
        12: 0.00034332275390625,
        11: 0.0006866455078125,
        10: 0.001373291015625,
        9: 0.00274658203125,
        8: 0.0054931640625,
        7: 0.010986328125,
        6: 0.02197265625,
        5: 0.0439453125,
        4: 0.087890625,
        3: 0.17578125,
        2: 0.3515625,
        1: 0.703125
    };
    var level = document.getElementById("level").value;

    var coef = tdtScale[level] * 256;
    var bounds = map.getBounds();
    var northWestLatlng = bounds.getNorthWest();
    var southEastLatlng = bounds.getSouthEast();

    var colmin = Math.round((northWestLatlng.lng - topTileFromX) / coef);
    var rowmin = Math.round((topTileFromY - northWestLatlng.lat) / coef);

    var colmax = Math.round((southEastLatlng.lng - topTileFromX) / coef);
    var rowmax = Math.round((topTileFromY - southEastLatlng.lat) / coef);
    var colcnt = colmax - colmin;
    var rowcnt = rowmax - rowmin;
    if ((colcnt * rowcnt) > 4000) {
        layer.msg("地图合成数量过大，请重新选择较小区块!");
        return;
    }
    var params = "type=" + layerType + "&level=" + level + "&colMin=" + colmin + "&rowMin=" + rowmin + "&colMax=" + colmax + "&rowMax=" + rowmax;
    var url = "/regionAllot/toMergeMap?" + params;


    //加载层
    layer.msg('合成中', {
        icon: 16
        , shade: 0.01
    });
    $.get(url, function (data) {
        layer.closeAll('loading');
        var filename = data;
        var downloadUrl = "/regionAllot/downLoadFile?filename=" + filename;
        window.location.href = downloadUrl;
    });
}
//地图下载PGIS
function toDowloadMapPgis(level) {
    var topTileFromX = 0;
    var topTileFromY = 0;

    var pgisScale = {
        20: 1.9073486328125E-06,
        19: 3.814697265625E-06,
        18: 7.62939453125E-06,
        17: 1.52587890625E-05,
        16: 3.0517578125E-05,
        15: 6.103515625E-05,
        14: 0.0001220703125,
        13: 0.000244140625,
        12: 0.00048828125,
        11: 0.0009765625,
        10: 0.001953125,
        9: 0.00390625,
        8: 0.0078125,
        7: 0.015625,
        6: 0.03125,
        5: 0.0625,
        4: 0.125,
        3: 0.25,
        2: 0.5,
        1: 1
    };

    var coef = pgisScale[level] * 256;
    var bounds = map.getBounds();
    var northEastLatlng = bounds.getNorthEast();
    var southWestLatlng = bounds.getSouthWest();

    var colmin = Math.round((southWestLatlng.lng - topTileFromX) / coef);
    var rowmin = Math.round((southWestLatlng.lat - topTileFromY) / coef);

    var colmax = Math.round((northEastLatlng.lng - topTileFromX) / coef);
    var rowmax = Math.round((northEastLatlng.lat - topTileFromY) / coef);
    var colcnt = colmax - colmin;
    var rowcnt = rowmax - rowmin;
    if ((colcnt * rowcnt) > 4000) {
        layer.msg("地图合成数量过大，请重新选择较小区块!");
        return;
    }
    var params = "type=" + layerType + "&level=" + level + "&colMin=" + colmin + "&rowMin=" + rowmin + "&colMax=" + colmax + "&rowMax=" + rowmax;
    var url = "/regionAllot/toMergeMap?" + params;


    //加载层
    layer.msg('合成中', {
        icon: 16
        , shade: 0.01
    });
    $.get(url, function (data) {
        layer.closeAll('loading');
        var filename = data;
        var downloadUrl = "/regionAllot/downLoadFile?filename=" + filename;
        window.location.href = downloadUrl;
    });
}
//地图下载
function toDowloadMapOffline(level) {
    var topTileFromX = -180;
    var topTileFromY = 90;

    var tdtScale = {
        20: 1.3411045074462875E-06,
        19: 2.682209014892575E-06,
        18: 5.36441802978515E-06,
        17: 1.07288360595703E-05,
        16: 2.1457672119140625E-05,
        15: 4.29153442382814E-05,
        14: 8.58306884765629E-05,
        13: 0.000171661376953125,
        12: 0.00034332275390625,
        11: 0.0006866455078125,
        10: 0.001373291015625,
        9: 0.00274658203125,
        8: 0.0054931640625,
        7: 0.010986328125,
        6: 0.02197265625,
        5: 0.0439453125,
        4: 0.087890625,
        3: 0.17578125,
        2: 0.3515625,
        1: 0.703125
    };

    var coef = tdtScale[level] * 256;
    var bounds = map.getBounds();
    var northWestLatlng = bounds.getNorthWest();
    var southEastLatlng = bounds.getSouthEast();

    var colmin = Math.round((northWestLatlng.lng - topTileFromX) / coef);
    var rowmin = Math.round((topTileFromY - northWestLatlng.lat) / coef);

    var colmax = Math.round((southEastLatlng.lng - topTileFromX) / coef);
    var rowmax = Math.round((topTileFromY - southEastLatlng.lat) / coef);
    var colcnt = colmax - colmin;
    var rowcnt = rowmax - rowmin;
    if ((colcnt * rowcnt) > 4000) {
        layer.msg("地图合成数量过大，请重新选择较小区块!");
        return;
    }
    var params = "type=" + layerType + "&level=" + level + "&colMin=" + colmin + "&rowMin=" + rowmin + "&colMax=" + colmax + "&rowMax=" + rowmax;
    var url = "/regionAllot/toMergeMap?" + params;


    //加载层
    layer.msg('合成中', {
        icon: 16
        , shade: 0.01
    });
    $.get(url, function (data) {
        layer.closeAll('loading');
        var filename = data;
        var downloadUrl = "/regionAllot/downLoadFile?filename=" + filename;
        window.location.href = downloadUrl;
    });
}
//地图下载
function toDowloadMapOnline(level) {
    if ($('#downLoadMap').css("disabled") == true) {
        layer.msg("正在下载中请耐心等待..");
        return;
    }
    var topTileFromX = -20037508.3427892;
    var topTileFromY = 20037508.3427892;
    var tdtScale = {
        18: 0.597164283559817,
        17: 1.19432856685505,
        16: 2.38865713397468,
        15: 4.77731426794937,
        14: 9.55462853563415,
        13: 19.1092570712683,
        12: 38.2185141425366,
        11: 76.4370282850732,
        10: 152.8740565704,
        9: 305.7481128,
        8: 611.49622628138,
        7: 1222.99245256249,
        6: 2445.98490512499,
        5: 4891.96981024998,
        4: 9783.93962049996,
        3: 19567.8792409999,
        2: 39135.7584820001,
        1: 78271.5169639999
    };

    var coef = tdtScale[level] * 256;

    var bounds = map.getBounds();
    var northWestLatlng = bounds.getNorthWest();
    var southEastLatlng = bounds.getSouthEast();

    var colmin = Math.round((lon2Mercator(northWestLatlng.lng) - topTileFromX) / coef);
    var rowmin = Math.round((topTileFromY - lat2Mercator(northWestLatlng.lat)) / coef);

    var colmax = Math.round((lon2Mercator(southEastLatlng.lng) - topTileFromX) / coef);
    var rowmax = Math.round((topTileFromY - lat2Mercator(southEastLatlng.lat)) / coef);

    var colcnt = colmax - colmin;
    var rowcnt = rowmax - rowmin;
    if ((colcnt * rowcnt) > 4000) {
        // alert("地图合成数量过大，请重新选择较小区块!");
        layer.msg("地图合成数量过大，请重新选择较小区块!");
        $('#downLoadMap').css("disabled", false);
        return;
    } else {
        $('#downLoadMap').css("disabled", true);
    }
    var params = "type=" + layerType + "&level=" + level + "&colMin=" + colmin + "&rowMin=" + rowmin + "&colMax=" + colmax + "&rowMax=" + rowmax;
    var url = "/regionAllot/toMergeMap?" + params;
    //加载层
    layer.msg('合成中...', {icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, time: 99999999999999});
    $.get(url, function (data) {
        var filename = data;
        var downloadUrl = "/regionAllot/downLoadFile?filename=" + filename;
        window.location.href = downloadUrl;
        layer.msg('合成中...', {icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, time: 9});
        $('#downLoadMap').css("disabled", false);
    });
}

